/**
 * Created by huangxiaolu on 2014/11/17.
 */
var http = require('http');
var fs = require('fs');
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
}
else {

    http.createServer(function(request, response) {
        var file = parseInt(request.url.substring(1));
        file = file % 200;
        file = String("000" + file).slice(-3);

        // read the file
        fs.readFile('../data/input'+file+'.txt', 'ascii', function(err, data) {
            if(err) {
                console.log(err);
                response.writeHead(400, {'Content-Type':'text/plain'});
                response.end();
            }
            else {
                var results = data.toString().split("\r\n");

                results.sort();
                response.writeHead(200, {'Content-Type': 'text/plain'});
                response.end('input'+file+'.txt\t' + results[(parseInt(results.length/2))]);
            }
        });
    }).listen(8880, function () {
        console.log('Server running at http://127.0.0.1:8880/');
    });
}
